<template>
  <el-dialog width="550px" title="编辑素材" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
    <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
      <el-form-item prop="typeId" label="选择分组">
        <el-cascader style="width:100%;" v-model="dialogForm.typeId" :options="parentTypeOptions" :props="parentProps"
          placeholder="请选择分组" />
      </el-form-item>
      <el-form-item prop="fileName" label="文件名称">
        <el-input v-model="dialogForm.fileName" placeholder="请输入文件名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandle">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
import api from '../api'
import { successDeal } from '@/utils/utils'
export default {
  setup(props, context) {
    const dialogFormRef = ref(null)

    const state = reactive({
      dialogFormVisible: false,
      dialogForm: {},
      parentTypeOptions: [],
      parentProps: {
        value: 'typeId',
        label: 'typeName',
        checkStrictly: true,
      },
      dialogFormRules: {
        fileName: [
          { required: true, message: '请输入文件名称', trigger: 'blur' },
        ],
      },
    })

    function dialogShow(data) {
      state.dialogForm = { ...data }
      getSucaiTree()
      state.dialogFormVisible = true
    }

    function getSucaiTree() {
      const obj = {

      }
      api.sucaiTypeLoadAll(obj).then(res => {
        if (res.code == '200') {
          state.parentTypeOptions = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function getParentType(parentTypeList) {
      return typeof parentTypeList == 'string' ? parentTypeList : parentTypeList[parentTypeList.length - 1]
    }

    function submitHandle() {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          const obj = {
            fileId: state.dialogForm.fileId,
            fileName: state.dialogForm.fileName || null,
            typeId: getParentType(state.dialogForm.typeId) || null,
          }
          api.sucaiModify(obj).then(res => {
            if (res.code == '200') {
              successDeal(res.msg)
              context.emit('dialogClose')
              state.dialogFormVisible = false
            } else {
              warningDeal(res.msg)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    }

    function dialogClose() {
      dialogFormRef.value && dialogFormRef.value.resetFields()
    }

    return {
      ...toRefs(state),
      dialogFormRef,
      dialogShow,
      submitHandle,
      dialogClose,
    }
  }
}
</script>

<style>
</style>